package com.shouthwind.springboottest.controller;

import com.shouthwind.springboottest.entity.Book;
import com.shouthwind.springboottest.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookHandler {

    @Autowired
    private BookRepository bookRepository;

    @GetMapping("/findAll/{page}/{size}") //restful风格
    @ResponseBody
    public Page<Book> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageRequest request=PageRequest.of(page,size);
        List<Book>  books=bookRepository.findAll();
        System.out.println(books.toString());
        return bookRepository.findAll(request);
    }

    @PostMapping("/save")
    @ResponseBody
    public String saveBook(@RequestBody Book book){ //前端传来的是json数据，@RequestBody可以将其转为Book类型

        System.out.println("存数据");
        Book result=bookRepository.save(book);
        if(result!=null){
            return "success";
        }else{
            return "error";
        }
    }


   @GetMapping("/findById/{id}")
   @ResponseBody
    public Book findById(@PathVariable("id") Integer id){
        return bookRepository.findById(id).get();
   }

   @PutMapping("/update")
   @ResponseBody
    public String update(@RequestBody Book book){ //前端传来的是json数据，@RequestBody可以将其转为Book类型
       System.out.println("修改数据");
       Book result=bookRepository.save(book);
       if(result!=null){
           return "success";
       }else{
           return "error";
       }
   }

   @DeleteMapping("/delete/{id}")
   @ResponseBody
    public void deleteById(@PathVariable("id") Integer id){
        bookRepository.deleteById(id);
   }
}















